package easy

/*
时间复杂度:O(N)
空间复杂度:O(C)
*/

func buddyStrings(s string, goal string) bool {
	if len(s) != len(goal) {
		return false
	}
	first, second := -1, -1
	flag := false
	var arr [26]int
	for i := range s {
		if s[i] != goal[i] {
			if first == -1 {
				first = i
			} else if second == -1 {
				second = i
			} else {
				return false
			}
		}
		arr[s[i]-'a']++
		if arr[s[i]-'a'] >= 2 {
			flag = true
		}
	}
	if s == goal && flag {
		return true
	}
	return second != -1 && s[first] == goal[second] && s[second] == goal[first]
}


/*
时间复杂度:O(N)
空间复杂度:O(C)

解2:
*/

func buddyStrings1(s string, goal string) bool {
	if len(s) != len(goal) {
		return false
	}
	var cnt1 [26]int
	var cnt2 [26]int
	sum := 0
	for i := range s {
		cnt1[s[i]-'a']++
		cnt2[goal[i]-'a']++
		if s[i] != goal[i] {
			sum++
		}
	}

	flag := false
	for i := 0; i < 26; i++ {
		if cnt1[i] != cnt2[i] {
			return false
		}
		if cnt1[i] >= 2 {
			flag = true
		}
	}
	return (sum == 0 && flag) || sum == 2
}